const { app, Menu, ipcMain, dialog } = require("electron");
const isDev = require("electron-is-dev");
const path = require("path");

const menuTemplate = require("./src/menuTemplate");
const AppWindow = require("./src/AppWindow");
const QiniuManager = require("./src/utils/QiniuManager");

const Store = require("electron-store");
// 初始化
Store.initRenderer();
const settingsStore = new Store({ name: "Settings" });
const fileStore = new Store({ name: "Files Data" });

// 实例化七牛云类
const createManager = () => {
    const accessKey = settingsStore.get("accessKey");
    const secretKey = settingsStore.get("secretKey");
    const bucketName = settingsStore.get("bucketName");
    return new QiniuManager(accessKey, secretKey, bucketName);
};

let mainWindow, settingsWindow;
app.on("ready", () => {
    const urlLocation = isDev ? "http://localhost:3000" : `file://${path.join(__dirname, "./build/index.html")}`;
    // 启用远程
    require("@electron/remote/main").initialize();

    // // 未抽象成class写法
    // mainWindow = new BrowserWindow({
    //     width: 1400,
    //     height: 800,
    //     webPreferences: {
    //         nodeIntegration: true,
    //         contextIsolation: false,
    //         enableRemoteModule: true,
    //     },
    // });
    // mainWindow.loadURL(urlLocation);

    // class
    const mainWindowConfig = {
        width: 1400,
        height: 800,
    };
    mainWindow = new AppWindow(mainWindowConfig, urlLocation);
    mainWindow.on("closed", () => {
        mainWindow = null;
    });

    // 在主进程中启用远程：
    require("@electron/remote/main").enable(mainWindow.webContents);

    // 设置菜单
    let menu = Menu.buildFromTemplate(menuTemplate);
    Menu.setApplicationMenu(menu);

    // 监听原生菜单发送的事件
    ipcMain.on("open-settings-window", () => {
        const settingsWindowConfig = {
            width: 500,
            height: 400,
            parent: mainWindow,
        };
        // const settingsFileLocation = `file://${path.join(__dirname, "./settings/settings.html")}`;
        const settingsFileLocation = `file://${path.join(__dirname, "./settings/settings.html")}`;
        settingsWindow = new AppWindow(settingsWindowConfig, settingsFileLocation);
        // 删除顶部菜单
        // settingsWindow.removeMenu();
        settingsWindow.on("closed", () => {
            settingsWindow = null;
        });
        // 在子进程中启用远程：
        require("@electron/remote/main").enable(settingsWindow.webContents);
    });

    // 监听上传事件。上传方法
    ipcMain.on("upload-file", (event, data) => {
        const manager = createManager();
        manager
            .uploadFile(data.key, data.path)
            .then((res) => {
                console.log("上传成功", res);
                // 上传成功后，给app.js发送事件
                mainWindow.webContents.send("active-file-uploaded");
            })
            .catch((err) => {
                console.log(err);
                dialog.showErrorBox("同步失败", err.body.error);
            });
    });

    // 下载文件
    ipcMain.on("download-file", (event, data) => {
        const manager = createManager();
        const filesObj = fileStore.get("files");
        const { key, path, id } = data;
        manager.getStat(data.key).then(
            (resp) => {
                // console.log(resp);
                // console.log(filesObj);
                // 七牛云的时间戳是纳秒，所以需要除10000，和普通的秒时间戳比较
                const serverUpdatedTime = Math.round(resp.putTime / 10000);
                // console.log("qiniu", serverUpdatedTime);
                const localUpdatedTime = filesObj[id].updatedAt;
                // console.log("local", localUpdatedTime);
                // 如果云文件更新时间大于本地文件的更新时间，或者本地文件没有更新时间。就从云直接下载
                if (serverUpdatedTime > localUpdatedTime || !localUpdatedTime) {
                    manager
                        .downloadFile(key, path)
                        .then(() => {
                            console.log("download-success 下载文件成功");
                            mainWindow.webContents.send("file-downloaded", { status: "download-success", id });
                        })
                        .catch((error) => {
                            // console.log(error);
                        });
                } else {
                    // 旧的文件
                    console.log("no-new-file 旧的文件");
                    mainWindow.webContents.send("file-downloaded", { status: "no-new-file", id });
                }
            },
            (error) => {
                // 如果error.statusCode 说明云没有这个文件
                if (error.statusCode === 612) {
                    console.log("no-file 云没有这个文件");
                    mainWindow.webContents.send("file-downloaded", { status: "no-file", id });
                }
            },
        );
    });

    // 全部上传云端
    ipcMain.on("upload-all-to-qiniu", () => {
        // console.log("upload-all-to-qiniu");
        mainWindow.webContents.send("loading-status", true);
        const filesObj = fileStore.get("files") || {};
        const manager = createManager();
        // 包含一系列上传方法的数组
        const uploadPromiseArr = Object.keys(filesObj).map((key) => {
            // 获取到单个的文件对象
            const file = filesObj[key];
            return manager.uploadFile(`${file.title}.md`, file.path);
        });
        Promise.all(uploadPromiseArr)
            .then((res) => {
                dialog.showMessageBox({
                    type: "info",
                    title: `上传成功`,
                    message: `上传了${res.length}个文件`,
                });
                mainWindow.webContents.send("files-uploaded");
            })
            .catch((err) => {
                dialog.showErrorBox("同步失败", err.body.error);
            })
            .finally(() => {
                mainWindow.webContents.send("loading-status", false);
            });
        // setTimeout(() => {
        //     mainWindow.webContents.send("loading-status", false);
        // }, 2000);
    });

    // 七牛云配置，三个值都填写时，云同步后三个按钮允许点击，否则不允许点击
    ipcMain.on("config-is-saved", () => {
        // 判断macos还是window，mac菜单前面多一个子菜单
        let qiniuMenu = process.platform === "darwin" ? menu.items[3] : menu.items[2];
        // 控制云同步子菜单下标123项点击
        const switchItems = (toggle) => {
            [1, 2, 3].forEach((index) => {
                qiniuMenu.submenu.items[index].enabled = toggle;
            });
        };
        // 判断 "accessKey", "secretKey", "bucketName" 是否都填写
        const qiniuIsConfiged = ["accessKey", "secretKey", "bucketName"].every((key) => !!settingsStore.get(key));
        if (qiniuIsConfiged) {
            switchItems(true);
        } else {
            switchItems(false);
        }
    });

    // 窗口最大化
    // mainWindow.maximize();

    // 打开开发者工具
    // mainWindow.webContents.openDevTools();
});
